<template>
  <div class="update-photo">
    <img :src="img" class="img" ref="imgRef"/>
    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { uploadPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  components: {},
  data () {
    return {
      cropper: null
    }
  },
  created () {

  },
  mounted () {
    const image = this.$refs.imgRef
    this.cropper = new Cropper(image, {
      viewMode: 1, // 限制裁剪框不超过画布的大小
      dragMode: 'move', // 移动画布
      aspectRatio: 1, // 定义裁剪框的固定宽高比。默认情况下，裁剪框具有自由比率。
      autoCropArea: 1, // 它应该是0到1之间的数字。定义自动裁剪区域大小（百分比）。
      cropBoxMovable: false, // 启用通过拖动移动裁剪框。
      cropBoxResizable: false, // 启用通过拖动调整裁剪框大小。
      background: false
    })
  },
  methods: {
    onConfirm () {
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {
        const formData = new FormData()
        formData.append('photo', blob)
        const { data: { data } } = await uploadPhoto(formData)
        console.log(data)
        // 修改父组件的数据
        this.$emit('update-photo', data.photo)
        // 关闭弹层
        this.$emit('close')
      })
    }
  }
}
</script>

<style lang="less" scoped>
img {
  max-width: 100%;
}
.update-photo {
      background-color: #000;
  height: 100%;
  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel, .confirm {
              width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
</style>
